// pages/contract-list/index.js
Page({
  data: {
    contractList: [],
    loading: false,
    empty: false
  },

  onLoad() {
    this.loadContractList();
  },

  onShow() {
    // 每次显示页面时刷新列表
    this.loadContractList();
  },

  // 下拉刷新
  async onPullDownRefresh() {
    await this.loadContractList();
    wx.stopPullDownRefresh();
  },

  // 加载合同列表
  async loadContractList() {
    this.setData({ loading: true, empty: false });
    try {
      const res = await wx.cloud.callFunction({
        name: 'contract',
        data: {
          apiType: 'getContractList'
        }
      });

      if (res.result.res.code === 200) {
        const contractList = res.result.res.data || [];
        // 格式化合同数据
        const formattedList = contractList.map(contract => {
          return {
            ...contract,
            startDateStr: this.formatStartDate(contract),
            statusText: this.getStatusText(contract.status),
            statusClass: this.getStatusClass(contract.status)
          };
        });

        this.setData({
          contractList: formattedList,
          loading: false,
          empty: formattedList.length === 0
        });
      } else {
        wx.showToast({
          title: res.result.res.msg || '加载失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      }
    } catch (error) {
      console.error('加载合同列表失败:', error);
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
      this.setData({ loading: false });
    }
  },

  // 格式化开始日期
  formatStartDate(contract) {
    if (contract.startYear && contract.startMonth && contract.startDay) {
      return `${contract.startYear}年${contract.startMonth}月${contract.startDay}日`;
    }
    return '未设置';
  },

  // 获取状态文本
  getStatusText(status) {
    const statusMap = {
      'pending': '未签约',
      'active': '已开始',
      'completed': '已结束',
      'terminated': '已废除'
    };
    return statusMap[status] || '未知';
  },

  // 获取状态样式类
  getStatusClass(status) {
    const classMap = {
      'pending': 'status-pending',
      'active': 'status-active',
      'completed': 'status-completed',
      'terminated': 'status-terminated'
    };
    return classMap[status] || '';
  },

  // 点击合同卡片，跳转到详情页
  onContractTap(e) {
    const contractId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/contract-detail/index?contractId=${contractId}`
    });
  }
});

